﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class instantiateball : MonoBehaviour {

	public GameObject ball;
    public GameObject Touch;
    public GameObject Shade;
    public Text scoreText;
    public GameObject AddBall;
    //public GameObject Title;
    public int number = 10;
	public bool nemberswitch = true;
	public static int score = 0;
    public static bool fail = false;
    // 单例实例
    public static instantiateball Instance { get; private set; }

    // 确保在游戏启动时创建唯一的实例
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);  // 如果已经存在实例，则销毁新的实例
        }
    }
    // Use this for initialization
    void Start () {
        // 添加触摸检测组件（如果不存在）
        if (Touch != null && Touch.GetComponent<Collider>() == null)
        {
            Touch.AddComponent<BoxCollider>();
        }

        // 为触摸对象添加事件触发器
        if (Touch != null)
        {
            var eventTrigger = Touch.GetComponent<EventTrigger>() ?? Touch.AddComponent<EventTrigger>();

            // 创建触摸响应事件
            var entry = new EventTrigger.Entry();
            entry.eventID = EventTriggerType.PointerDown;
            entry.callback.AddListener((data) => { OnTouchDetected(); });
            eventTrigger.triggers.Add(entry);
        }
    }
	
	// Update is called once per frame
	void Update () {
        // 更新UI文本，将剩余球数显示在T1、T2、T3上
        for (int i = 1; i <= 1; i++) {
			GameObject.Find("T" + i).GetComponent<Text>().text = (number - i + 1).ToString();
		}
        if (number <= 0) 
        {
            
        }
        scoreText.text = score.ToString();
	}

    // 触摸事件处理函数
    public void OnTouchDetected()
    {
        // 当剩余的球数大于0时
        if (number > 0 && !fail)
        {
            fail = true;
            number--;
        }
    }

    // 游戏胜利时调用的函数
    void winGame(){
		transform.GetComponent<LevelController> ().onWin ();
    }

    public void AddBalls() 
    {
        GameObject instantiatedBall = Instantiate(ball);

        // 设置实例化的 ball 为 AddBall 的子节点
        instantiatedBall.transform.SetParent(AddBall.transform, false);
    }

    public void SetShade(bool shade) 
    {
        Shade.SetActive(shade);
    }

    //进入下一关
    public void IsNextLevel() 
    {
        //if (number <= 0)
        //{
        //    if (nemberswitch)
        //    {
        //        Invoke("winGame", 1.0f);
        //        nemberswitch = false;
        //    }
        //}
        if (score >= PlayerPrefs.GetInt("x")*5&& PlayerPrefs.GetInt("x")<3)
        {
            if (nemberswitch)
            {
                Invoke("winGame", 1.0f);
                nemberswitch = false;
            }
        }
    }
}
